package com.hanlyjiang.library.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;

public class UtilsNetwork {

    protected static final String TAG = "UtilsNetwork";

    /**
     * 判断是否有可用网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * @param context
     * @return type or -1 (没有可用网络连接)
     */
    private static int getCurrentConnectedNetType(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = mConnectivityManager
                .getActiveNetworkInfo();
        if (activeNetwork != null) {
            return activeNetwork.getType();
        } else {
            return -1;
        }
    }

    public static boolean isUsingWifi(Context context) {
        int type = getCurrentConnectedNetType(context);
        return type == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean isUsingMobileData(Context context) {
        int type = getCurrentConnectedNetType(context);
        return type == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 判断wifi是否连接
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 移动网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 当前连接的网络类型
     *
     * @param context
     * @return 当前连接的网络类型；如果没有可用网络，返回-1； context为null，返回-1
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    /**
     * 监听网络状态变化的广播接收器
     *
     * @param context
     * @return
     */
    public static BroadcastReceiver createNetChangeReceiver(Context context) {

        BroadcastReceiver connectionReceiver = new BroadcastReceiver() {

            private boolean isNetworkDisconnected = false;

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "onReceive");
                if (intent.getAction().equals(
                        ConnectivityManager.CONNECTIVITY_ACTION)) {
                    Set<String> keys = intent.getExtras().keySet();
                    for (String key : keys) {
                        Log.d(TAG, key + ":" + intent.getExtras().get(key) + "; ");
                    }
                    NetworkInfo netInfo = intent.getExtras().getParcelable(ConnectivityManager.EXTRA_NETWORK_INFO);
//					if(netInfo.isConnected())
//					ConnectivityManager connectMgr = (ConnectivityManager) context
//							.getSystemService(Context.CONNECTIVITY_SERVICE);
//					NetworkInfo mobNetInfo = connectMgr
//							.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//					NetworkInfo wifiNetInfo = connectMgr
//							.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//					if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
//						// unconnect network
//					} else {
//						// connect network
//					}
                }
            }
        };
        return connectionReceiver;
    }


    public static InputStream openConnection(String s) throws IOException {
        final URL url = new URL(s);
//		Log.d("httpurl", "url="+s);
        URLConnection urlconnec = url.openConnection();
        urlconnec.setConnectTimeout(5000);
//		urlconnec.setReadTimeout(5000);
        return urlconnec.getInputStream();
    }

    public static byte[] readData(InputStream in) throws IOException {
        InputStream in1 = new BufferedInputStream(in, 8192);
        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        BufferedOutputStream out = new BufferedOutputStream(dataStream, 8192);
        copy(in1, out);
        out.flush();
        byte[] data = dataStream.toByteArray();
        return data;
    }

    private static int copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[8192];
        int read;
        int a = 0;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
            out.flush();
            a += read;
        }
        return a;
    }
}
